import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

const ExportToExcel= ({data, fileName}: any) => {
    const exportToExcel = () => {
        const ws= XLSX.utils.json_to_sheet(data); // Convert data to worksheet
        const wb= XLSX.utils.book_new(); // Create a new workbook
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // Append the worksheet to the workbook
        const wbout= XLSX.write(wb, {type:'binary', bookType:'xlsx'}); // Write the workbook to a binary string
        function s2ab(s: string) {
            const buf= new ArrayBuffer(s.length);
            const view= new Uint8Array(buf);
            for (let i=0;i!==s.length;++i) view[i]= s.charCodeAt(i) & 0xFF; // Convert the string to an array buffer
            return buf;
        }
        saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}), fileName+".xlsx"); // Save the file
    }
    return (
        <span onClick={exportToExcel}>导出数据</span>
    )
};

export default ExportToExcel